package 书店销售管理系统;

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.FlowLayout;
import java.awt.Graphics; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener;
import java.sql.Connection; 
import java.sql.DriverManager;
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.BorderFactory;
import javax.swing.JButton; 
import javax.swing.JDialog; 
import javax.swing.JFrame; 
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager; 
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class MemberManagement extends JFrame { 
	private static final long serialVersionUID = 1L; 
private JTable table;
private DefaultTableModel model;

private final String url = "jdbc:oracle:thin:@localhost:1521:xe";
private final String user = "HR";
private final String password = "123456";

public MemberManagement() {
    setTitle("会员信息管理");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(900, 700);
    setLocationRelativeTo(null);
    setLayout(new BorderLayout());

    // 设置背景
    JPanel background = new JPanel() {
        /**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		@Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // 绘制半透明粉色背景
            g.setColor(new Color(255, 192, 203, 128));
            g.fillRect(0, 0, getWidth(), getHeight());
        }
    };
    add(background, BorderLayout.CENTER);

    // 创建顶部面板
    JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
    topPanel.setOpaque(false); // 设置为透明背景

    // 创建菜单栏
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    // 添加下拉菜单
    JMenu dropDownMenu = new JMenu("菜单");
    menuBar.add(dropDownMenu);


    // 添加子菜单：销售信息管理
    JMenuItem salesItem = new JMenuItem("销售信息管理");
    salesItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // 在此添加跳转到“销售信息管理”界面的代码
            new SalesManagement().setVisible(true);
        }
    });
    dropDownMenu.add(salesItem);

    // 添加子菜单：图书信息管理
    JMenuItem bookItem = new JMenuItem("图书信息管理");
    bookItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // 在此添加跳转到“图书信息管理”界面的代码
            new Book().setVisible(true);
        }
    });
    dropDownMenu.add(bookItem);
    
    // 添加子菜单：会员信息管理
    JMenuItem memberItem = new JMenuItem("会员类别管理");
    memberItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // 在此添加跳转到“会员信息管理”界面的代码
            new VipTypeManagement().setVisible(true);
        }
    });
    dropDownMenu.add(memberItem);
     
    // 添加子菜单：会员类别管理
    JMenuItem memberItem1 = new JMenuItem("用户信息管理");
    memberItem1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // 在此添加跳转到“会员类别管理”界面的代码
            new UserManagement().setVisible(true);
        }
    });
    dropDownMenu.add(memberItem1);

    // 添加子菜单：退出
    JMenuItem exitItem = new JMenuItem("退出");
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            dispose(); // 关闭窗口
            System.exit(0); // 退出应用程序
        }
    });
    dropDownMenu.add(exitItem);

    // 添加按钮：添加、编辑、删除、查询
    JButton addButton = new JButton("Add");
    addButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            MemberDialog dialog = new MemberDialog(MemberManagement.this, "Add Member", null);
            if (dialog.isOK()) {
                addMember(dialog.getData());
            }
        }
    });
    topPanel.add(addButton);

    JButton editButton = new JButton("Edit");
    editButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int row = table.getSelectedRow();
            if (row >= 0) {
                String vno = (String) model.getValueAt(row, 0);
                Object[] data = { vno, model.getValueAt(row, 1), model.getValueAt(row, 2),
                        model.getValueAt(row, 3) };
                MemberDialog dialog = new MemberDialog(MemberManagement.this, "Edit Member", data);
                if (dialog.isOK()) {
                    editMember(dialog.getData());
                }
            } else {
                JOptionPane.showMessageDialog(MemberManagement.this, "请先选择要编辑的会员。");
            }
        }
    });
    topPanel.add(editButton);

    JButton deleteButton = new JButton("Delete");
    deleteButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int row = table.getSelectedRow();
            System.out.println(row);
            if (row >= 0) {
                String vno = (String) model.getValueAt(row, 0);
                int result = JOptionPane.showConfirmDialog(MemberManagement.this,
                        "你确定要删除会员 \"" + model.getValueAt(row, 2) + "\" 的信息吗？", "删除会员", JOptionPane.YES_NO_OPTION);
                if (result == JOptionPane.YES_OPTION) {
                    deleteMember(vno);
                }
            } else {
                JOptionPane.showMessageDialog(MemberManagement.this, "请先选择要删除的会员。");
            }
        }
    });
    topPanel.add(deleteButton);

    JTextField searchField = new JTextField(20);
    searchField.setHorizontalAlignment(JTextField.CENTER); // 设置文本框居中对齐
    searchField.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            searchMember(searchField.getText());
        }
    });
    topPanel.add(searchField);

    JButton searchButton = new JButton("Search");
    searchButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            searchMember(searchField.getText());
        }
    });
    topPanel.add(searchButton);

    // 添加顶部面板
    background.add(topPanel, BorderLayout.NORTH);

    // 创建表格
    String[] columnNames = { "会员号", "会员等级", "姓名", "电话" };
    model = new DefaultTableModel(columnNames, 0);
    table = new JTable(model) {
        private static final long serialVersionUID = 1L;

        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scrollPane = new JScrollPane(table);
    table.setPreferredScrollableViewportSize(new Dimension(800, 500));

    scrollPane.setOpaque(false);
    scrollPane.getViewport().setOpaque(false);
    background.add(scrollPane, BorderLayout.CENTER);

    refreshTable(); // 刷新表格
    setVisible(true);
}

private void refreshTable() {
    model.setRowCount(0); // 清空表格数据
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection conn = DriverManager.getConnection(url, user, password);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM VIP");
        while (rs.next()) {
            String vno = rs.getString("VNO");
            String vlevel = rs.getString("VLEVEL");
            String vname = rs.getString("VNAME");
            String phone = rs.getString("PHONE");
            model.addRow(new Object[] { vno, vlevel, vname, phone });
        }
        conn.close();
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
}

private void addMember(Object[] data) {
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection conn = DriverManager.getConnection(url, user, password);
        PreparedStatement pstmt = conn.prepareStatement(
                "INSERT INTO VIP (VNO, VLEVEL, VNAME, PHONE) VALUES (?, ?, ?, ?)");
        pstmt.setString(1, data[0].toString());
        pstmt.setString(2, data[1].toString());
        pstmt.setString(3, data[2].toString());
        pstmt.setString(4, data[3].toString());
        pstmt.executeUpdate();
        conn.close();
        refreshTable(); // 添加成功后刷新表格
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
}

private void editMember(Object[] data) {
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection conn = DriverManager.getConnection(url, user, password);
        PreparedStatement pstmt = conn.prepareStatement(
                "UPDATE VIP SET VLEVEL = ?, VNAME = ?, PHONE = ? WHERE VNO = ?");
        pstmt.setString(1, data[1].toString());
        pstmt.setString(2, data[2].toString());
        pstmt.setString(3, data[3].toString());
        pstmt.setString(4, data[0].toString());

        pstmt.executeUpdate();
        conn.close();
        refreshTable(); // 修改成功后刷新表格
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
}

private void deleteMember(String vno) {
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection conn = DriverManager.getConnection(url, user, password);
        PreparedStatement pstmt = conn.prepareStatement("DELETE FROM VIP WHERE VNO = ?");
        pstmt.setString(1, vno);
        pstmt.executeUpdate();
        conn.close();
        refreshTable(); // 删除成功后刷新表格
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
        }}

private void searchMember(String keyword) {
    model.setRowCount(0); // 清空表格数据
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection conn = DriverManager.getConnection(url, user, password);
        PreparedStatement pstmt = conn.prepareStatement(
                "SELECT * FROM VIP WHERE VNO LIKE ? OR VLEVEL LIKE ? OR VNAME LIKE ? OR PHONE LIKE ?");
        pstmt.setString(1, "%" + keyword + "%");
        pstmt.setString(2, "%" + keyword + "%");
        pstmt.setString(3, "%" + keyword + "%");
        pstmt.setString(4, "%" + keyword + "%");
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            String vno = rs.getString("VNO");
            String vlevel = rs.getString("VLEVEL");
            String vname = rs.getString("VNAME");
            String phone = rs.getString("PHONE");
            model.addRow(new Object[] { vno, vlevel, vname, phone });
        }
        conn.close();
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
}

// Dialog for adding/editing member information
private class MemberDialog extends JDialog {
    private static final long serialVersionUID = 1L;
    private JTextField vnoField, vlevelField, vnameField, phoneField;
    private JButton okButton, cancelButton;
    private boolean isOK;

    public MemberDialog(JFrame owner, String title, Object[] data) {
        super(owner, title, true);
        setSize(400, 300);
        setLocationRelativeTo(owner);
        setLayout(new BorderLayout());

        JPanel panel = new JPanel(new GridLayout(4, 2, 20, 20));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        add(panel, BorderLayout.CENTER);

        vnoField = new JTextField(20);
        panel.add(new JLabel("会员号："));
        panel.add(vnoField);

        vlevelField = new JTextField(20);
        panel.add(new JLabel("会员等级："));
        panel.add(vlevelField);

        vnameField = new JTextField(20);
        panel.add(new JLabel("姓名："));
        panel.add(vnameField);

        phoneField = new JTextField(20);
        panel.add(new JLabel("电话："));
        panel.add(phoneField);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        add(buttonPanel, BorderLayout.SOUTH);

        okButton = new JButton("确定");
        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                isOK = true;
                setVisible(false);
            }
        });
        buttonPanel.add(okButton);

        cancelButton = new JButton("取消");
        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                isOK = false;
                setVisible(false);
            }
        });
        buttonPanel.add(cancelButton);

        if (data != null) { // 如果是编辑，则将原始数据显示在文本框中
            vnoField.setText(data[0].toString());
            vlevelField.setText(data[1].toString());
            vnameField.setText(data[2].toString());
            phoneField.setText(data[3].toString());
        }
        setVisible(true);
    }

    public boolean isOK() {
        return isOK;
    }

    public Object[] getData() {
        return new Object[] { vnoField.getText(), vlevelField.getText(), vnameField.getText(),
                phoneField.getText() };
    }
}

public static void main(String[] args) {
    try {
        for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
            | UnsupportedLookAndFeelException e) {
        e.printStackTrace();
    }
    new MemberManagement();
}
}